package com.eds.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codingapi.txlcn.tc.annotation.TccTransaction;
import com.eds.dto.CourseReviewDTO;
import com.eds.exception.BusException;
import com.eds.feign.OrderFeign;
import com.eds.feign.UserService;
import com.eds.mapper.CourseBookingMapper;
import com.eds.mapper.CourseReviewMapper;
import com.eds.pojo.BaseResult;
import com.eds.pojo.CodeEnum;
import com.eds.service.CourseReviewService;
import com.eds.service.CourseService;
import com.eds.utils.SnowflakeIdGenerator;
import com.pojo.CourseBooking;
import com.pojo.CourseReview;
import com.pojo.Orders;
import com.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;

/**
 * @author 34195
 * @description 针对表【course_review(课程评价表)】的数据库操作Service实现
 * @createDate 2025-04-06 05:18:49
 */
@Service
public class CourseReviewServiceImpl extends ServiceImpl<CourseReviewMapper, CourseReview>
        implements CourseReviewService {
    @Autowired
    private UserService userService;
    @Autowired
    private CourseReviewMapper courseReviewMapper;
    @Autowired
    private CourseBookingMapper courseBookingMapper;
    @Autowired
    private CourseService courseService;
    @Autowired
    private OrderFeign orderFeign;
    @Autowired
    private SnowflakeIdGenerator idGenerator;

    /* *
     * @Title: insertCourseReview
     * @Author: vvSmile
     * @Date: 2025-04-06 18:17:41
     * @param token
     * @param courseReview
     * @return CourseReviewDTO
     * @Description: TODO 新增课程评价
     */
    @Override
    @Transactional
    @TccTransaction
    public BaseResult insertCourseReview(String token, CourseReview courseReview) {
        //获取用户信息
        Long userId = userService.getUserIdFromToken(token);
        if (userId == null) {
            throw new BusException(CodeEnum.TOKEN_IS_NULL.getCode(), CodeEnum.TOKEN_IS_NULL.getMessage());
        }
        //查预约记录
        CourseBooking courseBooking = courseBookingMapper.selectById(courseReview.getBookingId());
        //查询订单信息
        Orders orders = orderFeign.selectOrdersByScheduleUserCourseId(courseBooking.getScheduleId(), userId, courseReview.getCourseId());
        //检查订单状态
        if (!userId.equals(courseBooking.getStudentId()) &&
                courseBooking.getStatus() != 3 && orders.getStatus() != 1) {
            return BaseResult.error(CodeEnum.REVIEW_ERROR);
        }
      /*  //查询是否已经评论过
        QueryWrapper<CourseReview> reviewQueryWrapper = new QueryWrapper<>();
        reviewQueryWrapper.eq("booking_id", courseReview.getBookingId())
                .eq("course_id", courseReview.getCourseId())
                .eq("student_id", userId)
                .eq("teacher_id", courseReview.getTeacherId())
                .eq("parent_id", 0);
        CourseReview selCourseReviewReturn = courseReviewMapper.selectOne(reviewQueryWrapper);
*/
        //如果存在，则新增课程评价
        CourseReview insertCourseReview = new CourseReview();
        //通过雪花算法生成课程ID
        //String notificationId = idGenerator.nextShortId(14);
        //新增评价（设置parent_id=0）
        //insertCourseReview.setReviewId(Long.parseLong(notificationId));
        insertCourseReview.setBookingId(courseReview.getBookingId());
        insertCourseReview.setCourseId(courseReview.getCourseId());
        insertCourseReview.setStudentId(userId);
        insertCourseReview.setTeacherId(courseBooking.getTeacherId());
        insertCourseReview.setRating(courseReview.getRating());
        insertCourseReview.setContent(courseReview.getContent());
        insertCourseReview.setStatus("1");
        insertCourseReview.setParentId(0L);
        insertCourseReview.setCreatedTime(new Date());
        insertCourseReview.setUpdatedTime(new Date());
        int insert = courseReviewMapper.insert(insertCourseReview);
        if (insert > 0) {
            //更新Course_booking表
            UpdateWrapper<CourseBooking> courseBookingUpdateWrapper = new UpdateWrapper<>();
            courseBookingUpdateWrapper.set("status", 4)
                    .eq("booking_id", courseBooking.getBookingId());
            int updateCourseBooking = courseBookingMapper.update(null, courseBookingUpdateWrapper);
            if (updateCourseBooking <= 0) {
                return BaseResult.error(CodeEnum.REVIEW_ERROR);
            }
            return BaseResult.ok("评论成功", insertCourseReview);
        } else {
            return BaseResult.error(CodeEnum.REVIEW_ERROR);
        }

    }


    /* *
     * @Title: replyCourseReview
     * @Author: vvSmile
     * @Date: 2025-04-06 18:17:53
     * @param token
     * @param courseReview
     * @return CourseReviewDTO
     * @Description: TODO 回复课程评价
     */
    @Override
    public BaseResult replyCourseReview(String token, CourseReview courseReview) {
        //获取用户信息
        Long userId = userService.getUserIdFromToken(token);
        if (userId == null) {
            throw new BusException(CodeEnum.TOKEN_IS_NULL.getCode(), CodeEnum.TOKEN_IS_NULL.getMessage());
        }
        //查预约记录
        CourseBooking courseBooking = courseBookingMapper.selectById(courseReview.getBookingId());
        //查询订单信息
        Orders orders = orderFeign.selectOrdersByScheduleUserCourseId(courseBooking.getScheduleId(), userId, courseReview.getCourseId());
        //检查订单状态
        //查询course_booking表，确认当前用户是否参与了该课程的预约。
        //检查预约状态：确保course_booking表中的status为已完成（即值为3）。
        //检查父级评论是否存在：查询course_review表，确认parent_id对应的评论是否存在且状态为正常。
        QueryWrapper<CourseReview> reviewQueryWrapper = new QueryWrapper<>();
        reviewQueryWrapper.eq("review_id", courseReview.getParentId())
                .eq("course_id", courseReview.getCourseId())
                .eq("teacher_id", courseBooking.getTeacherId())
                .eq("status", "1");
        CourseReview selCourseReviewReturn = courseReviewMapper.selectOne(reviewQueryWrapper);
        if (selCourseReviewReturn == null) {
            return BaseResult.error(CodeEnum.REVIEW_ERROR);
        }
        //插入回复：向course_review表中插入一条新的记录，将parent_id设置为被回复的评论的ID
        CourseReview insertCourseReview = new CourseReview();
        //新增评价（设置parent_id=0）
        insertCourseReview.setBookingId(courseReview.getBookingId());
        insertCourseReview.setCourseId(courseReview.getCourseId());
        insertCourseReview.setStudentId(userId);
        insertCourseReview.setTeacherId(courseBooking.getTeacherId());
        insertCourseReview.setRating(courseReview.getRating());
        insertCourseReview.setContent(courseReview.getContent());
        insertCourseReview.setStatus("1");
        insertCourseReview.setParentId(courseReview.getParentId());
        insertCourseReview.setCreatedTime(new Date());
        insertCourseReview.setUpdatedTime(new Date());
        int insertCourseReviewReturn = courseReviewMapper.insert(insertCourseReview);
        if (insertCourseReviewReturn > 0) {
            return BaseResult.ok("评论成功", insertCourseReview);
        } else {
            return BaseResult.error(CodeEnum.REVIEW_ERROR);
        }
    }


    /* *
     * @Title: deleteCourseReview
     * @Author: vvSmile
     * @Date: 2025-04-06 18:18:02
     * @param token
     * @param reviewId
     * @return boolean
     * @Description: TODO 删除课程评论
     */
    @Override
    public boolean deleteCourseReview(String token, Long reviewId) {
        //获取用户信息
        Long userId = userService.getUserIdFromToken(token);
        if (userId == null) {
            throw new BusException(CodeEnum.TOKEN_IS_NULL.getCode(), CodeEnum.TOKEN_IS_NULL.getMessage());
        }
        CourseReview courseReview = courseReviewMapper.selectById(reviewId);
        //检查用户权限
        if (courseReview == null || !courseReview.getStudentId().equals(userId)) {
            return false;
        }
        //删除评论：根据review_id从course_review表中删除记录。
        UpdateWrapper<CourseReview> courseReviewUpdateWrapper = new UpdateWrapper<CourseReview>()
                .eq("review_id", reviewId)
                .set("status", "0");
        int update = courseReviewMapper.update(null, courseReviewUpdateWrapper);
        //删除子评论
        UpdateWrapper<CourseReview> courseReviewUpdateWrapper1 = new UpdateWrapper<CourseReview>()
                .eq("parent_id", reviewId)
                .set("status", "1");
        for (CourseReview review : courseReviewMapper.selectList(courseReviewUpdateWrapper1)) {
            if (review != null) {
                UpdateWrapper<CourseReview> courseReviewUpdateWrapper2 = new UpdateWrapper<CourseReview>()
                        .eq("review_id", review.getReviewId())
                        .set("status", "0");
                courseReviewMapper.update(null, courseReviewUpdateWrapper2);
            }
        }

        return update > 0;
    }

    /* *
     * @Title: getCourseReviewList
     * @Author: vvSmile
     * @Date: 2025-04-06 18:18:23
     * @param courseId
     * @return ArrayList<CourseReviewDTO>
     * @Description: TODO 获取课程评论列表
     */
    @Override
    public ArrayList<CourseReviewDTO> getCourseReviewList(Long courseId) {
        //创建存储DTO的列表
        ArrayList<CourseReviewDTO> courseReviewDTOList = new ArrayList<>();
        //查询course_review表，获取指定course_id的评论列表。
        for (CourseReview courseReview : courseReviewMapper.selectList(new QueryWrapper<CourseReview>().eq("course_id", courseId).eq("status", "1").eq("parent_id", 0))) {
            //获取评论对应的用户信息
            User teacher = userService.getUserByUserId(courseReview.getTeacherId());
            User student = userService.getUserByUserId(courseReview.getStudentId());
            //创建DTO对象，并添加到列表中
            courseReviewDTOList.add(new CourseReviewDTO(courseReview, student.getUserName(), student.getOssImages().get(0).getUrl(), teacher.getUserName(), teacher.getOssImages().get(0).getUrl()));
        }
        return courseReviewDTOList;
    }


    /* *
     * @Title: getCourseReviewReplyList
     * @Author: vvSmile
     * @Date: 2025-04-06 18:18:35
     * @param reviewId
     * @return ArrayList<CourseReviewDTO>
     * @Description: TODO 获取课程评论回复列表
     */
    @Override
    public ArrayList<CourseReviewDTO> getCourseReviewReplyList(Long reviewId) {
        //创建存储DTO的列表
        ArrayList<CourseReviewDTO> courseReviewDTOList = new ArrayList<>();
        //根据review_id查询course_review表，获取指定评论的回复列表。
        for (CourseReview courseReview : courseReviewMapper.selectList(new QueryWrapper<CourseReview>()
                .eq("parent_id", reviewId)
                .eq("status", "1"))) {
            //获取回复对应的用户信息
            User teacher = userService.getUserByUserId(courseReview.getTeacherId());
            User student = userService.getUserByUserId(courseReview.getStudentId());
            //创建DTO对象，并添加到列表中
            courseReviewDTOList.add(new CourseReviewDTO(courseReview, student.getUserName(), student.getOssImages().get(0).getUrl(), teacher.getUserName(), teacher.getOssImages().get(0).getUrl()));
        }
        return courseReviewDTOList;
    }
}




